<?php

namespace App\Services\BoughtVip;

use Carbon\Carbon;
use App\Models\User;
use App\Models\VipPurchase;
use Illuminate\Support\Facades\DB;
use App\Events\VipPurchasePaidEvent;

class BoughtVip
{
	protected ?User $user = null;

	public function __construct($user)
	{
		
		$this->user = $user instanceof User ? $user : User::find($user);
	}

	

	public function recharge()
	{
		DB::transaction(function () {
			
			$vipExpiredAt = $this->user->vipExpiryAfterBuying();
			
			$reason = 'VIP会员续费';
			$this->user->update(['vip_expired_at' => $vipExpiredAt]);
			$this->user->upgradeLogs()->create([
				'reason' => $reason,
				'vip_expired_at' => $vipExpiredAt
			]);
		});
	}


	public function upgradeToVip()
	{
		if ($this->user->is_locked) {return;}
		
		if ($this->user->isNotVip()) {
			DB::transaction(function () {
				
				$vipExpiredAt = Carbon::now()->addDays(cs('sale')->vip_period)->hours(23)->minutes(59)->seconds(59);
				
				$this->user->upgradeLogs()->create([
					'reason' => '付费升级为VIP会员',
					'vip_expired_at' => $vipExpiredAt
				]);
				
				$this->user->update([
					'grade' => 'vip',
					'grade_level' => 0,
					'vip_expired_at' => $vipExpiredAt,
					'rewarded_at'=>time(),
				]);
			});
		}
	}
	
	
	
	public function make()
	{
		if ($this->user->isVip() and $this->user->vipPurchases()->whereNotNull('paid_at')->whereNull('cancelled_at')->count() > 1) {
			// bought as recharge.
			$this->recharge();
		} else {
			// bought as new vip.
			$this->upgradeToVip();
		}

		if($this->user->parent){

			 user_upgrade($this->user->parent);
		}
		
		
		
		
	}
}
